import { imgLoad, Log } from "../../common/utils/utils.js"

const lg = new Log('我是页面1');

export default {
  data: {
    title: "",
    imgList: [],
    imgLen: 64, // 序列帧图片的长度
    w: 360,
    h: 270,
    startPoint: 0, //触摸初始位置点
    unit: 360/(64 * 2), //滑动的精度单位
    imgIndex: 1, // 当前显示的图片下标
    startIndex: 1, // 从哪张图片开始
    ctx: null,
  },
  onInit() {
  },
  onShow(){
    this.initCanvas();
  },
  touchStart(e){
    let s = e.touches[0].localX;
    this.startPoint = s;
//    lg.log('触摸开始：',s);
  },
  touchMove(e){
    let s = e.touches[0].localX;
    if((s - this.startPoint) > this.unit){
      this.drawImg(this.imgIndex, 'left')
      this.startPoint = s;
      lg.log('向右：',s)
    } else if((s - this.startPoint) < -this.unit){
      this.drawImg(this.imgIndex, 'right')
      this.startPoint = s;
      lg.log('向左：',s)
    }
    this.startPoint = s;
  },
  initCanvas(){
    let c = this.$refs.canvas;
    this.ctx = c.getContext('2d');

    let arr = [];
    for(var i = 1; i <= this.imgLen; i++){
      arr.push(`common/images/car/${i}.png`)
    }
    imgLoad(arr,(img, progress) => {
      lg.log('进度：' + progress);
      this.imgList.push(img);
    },() => {
      lg.log('全部加载完成')
      this.cutSpirit();
    })
  },
  drawImg(n,type){
    if(type == "left"){
      if(this.imgIndex > 0){
        this.imgIndex--;
      }else{
        this.imgIndex = this.imgLen;
      }
    }else if(type == "right"){
      if(this.imgIndex < this.imgLen){
        this.imgIndex++;
      }else{
        this.imgIndex = this.startIndex;
      }
    }
    this.ctx.clearRect(0,0,this.w,this.h);
    this.ctx.drawImage(this.imgList[this.imgIndex],0,0,this.w,this.h);
  },
  //操作精灵
  cutSpirit(){
    this.ctx.clearRect(0,0,this.w,this.h);
    this.ctx.drawImage(this.imgList[this.imgIndex],0,0,this.w,this.h);
  },

}
